/**
 * Created by yujianfu on 2016/11/10.
 */
import React, {Component, PropTypes} from 'react'
import {Card, Icon, Modal, Form, Input, message, Button} from 'antd'
import Styles from '../../../finance/common/detail/Index.less'
import {fetchPost} from '../../../../utils/request'

const FormItem = Form.Item;

class BasicInfo extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      userId: props.userId,
      tradeNo: props.tradeNo,
      stepType: props.stepType,
      data: [],
      message: '',
      timer: null,
      visible: false,
      type: null,
    }
  }

  showModal = (type, e) => {
    this.setState({
      visible: true,
      type: type,
    });
  }

  handleOk = (e) => {
    let self = this;
    this.props.form.validateFields((error, values) => {
      if (!error) {
        this.updatePermanentAddress(values);
      } else {
        self.props.form.resetFields();
      }
    })
  }

  updatePermanentAddress(values) {
    let params;
    params = {
      ...values,
      type: this.state.type,
    }

    fetchPost(`/user/${this.state.tradeNo}/update/base/info`, params).then(json => {
      if (json.code == 0) {
        message.info("update success");
        this.setState({
          visible: false,
        }, () => {
          this.setState({
            type: null,
          })
        });
        this.getData();
      } else {
        message.error(json.msg);
      }
    });

  }

  handleCancel = (e) => {
    this.setState({
      visible: false,
    }, () => {
      this.setState({
        type: null,
      })
    });
    this.props.form.resetFields();
  }

  componentWillReceiveProps(props) {
    if (this.state.userId !== props.userId) {
      this.setState({
        userId: props.userId,
        tradeNo: props.tradeNo,
      }, () => {
        this.getData()
      })
    }
  }

  componentDidMount() {
    this.getData()
  }

  componentWillUnmount() {
    clearTimeout(this.state.timer)
  }

  getData() {
    if (this.state.tradeNo != null) {
      fetchPost(`/user/${this.state.tradeNo}/base/info`, {}).then(json => {
        if (json.data != null && json.code === 0) {
          this.setState({
            data: json.data.list
          })
        } else {
          this.setState({
            message: json.msg,
            data: []
          })
        }
      })
    } else {
      this.setState({
        data: []
      })
    }
  }

  createContent() {
    let data = this.state.data
    let self = this;
    let content = []
    if (data != null && data.length > 0) {
      data.map(function (item) {
        if (item.flag === 'basic') {
          let value = item.value
          if (value == null) {
            value = '--'
          }
          // 1 - permanent address 2 - current address
          if (item.name === 'Permanent Address' && (self.state.stepType != 'reeditOrder' && self.state.stepType != 'refuseOrder' && self.state.stepType != 'passOrder')) {
            content.push(
              <div key={item.name} className={Styles.content}>

                <span style={{width: '20%'}}>{item.name}</span>
                :
                <span style={{width: '80%', paddingLeft: 5}}>
                  <a onClick={self.showModal.bind(this, '1')}>{value}</a>
                </span>
              </div>)
          } else if (item.name === 'Address' && (self.state.stepType != 'reeditOrder' && self.state.stepType != 'refuseOrder' && self.state.stepType != 'passOrder')) {
            content.push(
              <div key={item.name} className={Styles.content}>

                <span style={{width: '20%'}}>{item.name}</span>
                :
                <span style={{width: '80%', paddingLeft: 5}}>
                  <a onClick={self.showModal.bind(this, '2')}>{value}</a>
                </span>
              </div>)
          } else {
            content.push(
              <div key={item.name} className={Styles.content}>

                <span style={{width: '20%'}}>{item.name}</span>
                :
                <span style={{width: '80%', paddingLeft: 5}}>{value}</span>
              </div>)
          }
        }
      })
    }
    return content
  }

  getTitle() {
    let data = this.state.data
    if (!data || !data.length) {
      return 'non data'
    }

    return 'person profile info'
  }

  message() {
    if (this.state.message) {
      this.state.timer = setTimeout(() => {
        this.setState({
          message: ''
        })
      }, 3000)
      return (
        <span className='color-warning warning-animate'><Icon type='info-circle-o'/> {this.state.message}</span>
      )
    } else {
      return ''
    }
  }


  render() {
    const {getFieldDecorator} = this.props.form;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 17},
    };

    return (
      <div className={Styles.detailModule}>
        <Card extra={this.message()} bodyStyle={{padding: 0}} noHovering={true}>
          {this.createContent()}
        </Card>

        <Modal
          title={this.state.type == '1' ? "Update Permanent Address" : "Update Current Address"}
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          okText="Update"
        >
          {
            this.state.type == '1' ?
              <Form style={{width: '100%', margin: 'auto'}} horizontal>
                <FormItem
                  {...formItemLayout}
                  label="New Address"
                >
                  {getFieldDecorator('permanentAddress', {
                    rules: [
                      {required: true, message: 'permanent address is necessary!'},
                    ],
                    initialValue: this.state.data != null && this.state.data.filter(item => item.flag === 'basic' && item.name === 'Permanent Address') != null
                    && this.state.data.filter(item => item.flag === 'basic' && item.name === 'Permanent Address')[0] != null
                      ? this.state.data.filter(item => item.flag === 'basic' && item.name === 'Permanent Address')[0]['value']
                      : ''
                  })(
                    <Input type='textarea'/>
                  )}
                </FormItem>
              </Form> :
              <Form style={{width: '100%', margin: 'auto'}} horizontal>
                <FormItem
                  {...formItemLayout}
                  label="New Address"
                >
                  {getFieldDecorator('currentAddress', {
                    rules: [
                      {required: true, message: 'current address is necessary!'},
                    ],
                    initialValue: this.state.data != null && this.state.data.filter(item => item.flag === 'basic' && item.name === 'Address') != null
                    && this.state.data.filter(item => item.flag === 'basic' && item.name === 'Address')[0] != null
                      ? this.state.data.filter(item => item.flag === 'basic' && item.name === 'Address')[0]['value']
                      : ''
                  })(
                    <Input type='textarea'/>
                  )}
                </FormItem>
              </Form>

          }


        </Modal>
      </div>

    )
  }
}

BasicInfo = Form.create()(BasicInfo)
export default BasicInfo
